/**
 * MasicParameter
 * <p/>
 * User: joakimd
 * Date: 2013-03-11
 * Time: 11:57
 */
package org.dru.masic {
import flash.events.Event;

public final class MasicParameter extends MasicMember {
    private var _steps: int;
    private var _initialValue: Number;
    private var _value: Number;
    private var _encoder: Function;
    private var _decoder: Function;

    public function MasicParameter(parent: MasicComponent, name: String, steps: int, value: Number, encoder: Function, decoder: Function) {
        super(parent, name);
        _steps = steps;
        _initialValue = value;
        _value = value;
        _encoder = encoder;
        _decoder = decoder;
    }

    public function get steps(): int {
        return _steps;
    }

    public function set steps(value: int): void {
        if (value < 0) {
            throw new Error("negative steps");
        }
        if (value != _steps) {
            _steps = value;
            notifyChange();
        }
    }

    public function get initialValue(): Number {
        return _initialValue;
    }

    public function get value(): Number {
        return _value;
    }

    public function set value(value: Number): void {
        if (value != _value) {
            _value = value;
            notifyChange();
        }
    }

    public function resetValue(): void {
        value = initialValue;
    }

    public function notifyChange(): void {
        dispatchEvent(new Event(Event.CHANGE));
    }

    public function integer(value: Number): int {
        return int(Math.round(value * Number(steps - 1)));
    }

    public function decimal(value: int): Number {
        return (steps > 1 ? Number(value) / Number(steps - 1) : 0.0);
    }

    public function encode(value: Number): String {
        return _encoder(value);
    }

    public function decode(value: String): Number {
        return _decoder(value);
    }
}
}
